package com.zky.gulimall.order.interceptor;

import com.zky.common.constant.AuthServerConstant;
import com.zky.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Description 用户登录拦截器
 * @Author 张开源
 * @Date 2022/12/9 11:39
 * @Version 1.0
 **/
@Component
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {

    private static String LOGIN_URL = "http://auth.zky.com/login.html";

    public static ThreadLocal<MemberRespVo> threadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //服务间调用请求无需登陆，uri过滤
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/order/**", request.getRequestURI());
        //异步通知的也过滤掉，不检验登陆
        boolean notify = antPathMatcher.match("/payed/notify", request.getRequestURI());

        if (match || notify) {
            return true;
        }
        HttpSession session = request.getSession();
        MemberRespVo memberRespVo = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberRespVo == null) {
            //用户没登陆,重定向去登陆
            log.warn("order 未登陆");
            session.setAttribute("msg", "请先登录");
            response.sendRedirect(LOGIN_URL);
            return false;
        }
        //已经登陆
        log.warn("order 已登录,memberRespVo:{}", memberRespVo);
        log.warn("已登录，当前线程name:{},当前线程id:{}", Thread.currentThread().getName(), Thread.currentThread().getId());
        threadLocal.set(memberRespVo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}
